#include "DisplayMainwindow.h"
//#include "./ui_mainwindow.h"


#include <QDebug>
#include <QFileInfo>
#include <QFile>
#include <QDir>
#include <QMenu>
#include <QStandardPaths>
#include <QProcess>
#include <QClipboard>
#include <QStandardItemModel>
#include <QToolBar>
#include <QGridLayout>
#include <QMainWindow>
#include <QHeaderView>
#include <QMessageBox>
#include <cstdlib>
#include <QThread>
#include <QStackedWidget>
#include <QMenuBar>
#include <QPushButton>
#include <QStandardItem>
#include <QTreeView>
#include <QFileIconProvider>
#include <QStyledItemDelegate>
#include <QProgressDialog>
#include <QtConcurrent/QtConcurrent>
#include <QToolTip>
#include <QLabel>
#include "MountWidget.h"

class MyItemDelegate : public QStyledItemDelegate {
public:
    QSize sizeHint(const QStyleOptionViewItem &option, const QModelIndex &index) const override {
        // 返回每个项的大小
        return QSize(100, 100);  // 根据需要调整大小
    }
};

//zzh改
MyListView::MyListView(QWidget* parent)
    : QListView(parent)
{
    setAcceptDrops(true);  // 启用拖拽接受操作
    setDragEnabled(true);  // 启用拖拽操作
    setDragDropMode(QAbstractItemView::DragDrop);  // 设置拖拽模式为 DragDrop
}
//


CustomWindow::CustomWindow(const QString& path,QWidget *parent)
    : QWidget(parent)
{
    setAcceptDrops(true);
    setMinimumSize(800, 470);
    setWindowTitle("审计移动存储安全平台");
    setWindowIcon(QIcon(":/icons/images/Upan2.png"));

    stackedWidget = new QStackedWidget(this);

    QToolBar *toolBar = new QToolBar(this);
    toolBar->setOrientation(Qt::Vertical);
    toolBar->setFixedWidth(35);
    toolBar->setIconSize(QSize(28, 28));
    QAction *changeway = new QAction(QIcon(":/icons/images/fold.png"),"切换布局",this);
    changeway->setToolTip("切换布局");
    connect(changeway, &QAction::hovered, this, [changeway](){
        QToolTip::showText(QCursor::pos(), changeway->toolTip());
    });
    toolBar->addAction(changeway);
    toolBar->addSeparator();
    QAction *uninstall = new QAction(QIcon(":/icons/images/alarm.png"),"U盘卸载",this);
    uninstall->setToolTip("U盘卸载");
    connect(uninstall, &QAction::hovered, this, [uninstall](){
        QToolTip::showText(QCursor::pos(), uninstall->toolTip());
    });
    connect(uninstall,&QAction::triggered,this,&CustomWindow::uninstallActionTriggered);
    toolBar->addAction(uninstall);
    toolBar->addSeparator();


    this->path = path;
    QVBoxLayout  *layoutMax = new QVBoxLayout (this);
    layoutMax->setContentsMargins(0, 0, 5, 5);
    QHBoxLayout  *layout = new QHBoxLayout (this);
    layout->setContentsMargins(0, 0, 0, 0);
    model = new QFileSystemModel(this);   
    QString rootPath = this->path;  // 指定要显示的目录路径
    qDebug()<<"rootPath == "<< rootPath;
    model->setRootPath(rootPath);


    treeView = new QTreeView(this);
    treeView->setModel(model);
    treeView->setRootIndex(model->index(rootPath));
    treeView->setCurrentIndex(model->index(rootPath));
    int currentWidth = treeView->columnWidth(1);
    treeView->setColumnWidth(0, 750-currentWidth*3-50);

    QWidget *listViewContainer = new QWidget();
    QVBoxLayout *listViewLayout = new QVBoxLayout(listViewContainer);
    listViewLayout->setContentsMargins(0, 0, 0, 0);

    listView = new MyListView(this);
    listView->setFlow(QListView::LeftToRight);
    listView->setViewMode(MyListView::IconMode);
    listView->setIconSize(QSize(100, 100));
    //listView->setSpacing(5);
    listView->setFixedHeight(420);
    listView->setWordWrap(true);
    listView->setModel(model); //设置树状结构的模型
    listView->setRootIndex(model->index(rootPath));
    listView->setCurrentIndex(model->index(rootPath));
    MyItemDelegate *itemDelegate = new MyItemDelegate();
    listView->setItemDelegate(itemDelegate);
    listView->setDragDropMode(QAbstractItemView::NoDragDrop);
    listViewLayout->addWidget(listView);

    QPushButton *returntop1 =new QPushButton("返回上一级目录",this);
//    QString buttonStyle = "QPushButton { background-color: #ADD8E6;  border-radius: 2px; }";
//    returntop1->setStyleSheet(buttonStyle);

    connect(returntop1, &QPushButton::clicked, this, &CustomWindow::onButtonClick);
    listViewLayout->addWidget(returntop1);
    // 根索引为空表示显示所有盘符
    stackedWidget->addWidget(treeView);
    stackedWidget->addWidget(listViewContainer);

//    QLabel *la = new QLabel("");
    layout->addWidget(toolBar);
    layout->addWidget(stackedWidget);
    //layout->addWidget(la);

    connect(treeView, &QTreeView::doubleClicked, this, &CustomWindow::openFile);

    //菜单
    contextMenu = new QMenu(this);
    //QAction* CopyAction = contextMenu->addAction("复制");
    QAction* PasteAction = contextMenu->addAction("粘贴");
    //QAction* ClippingAction = contextMenu->addAction("剪切");
    //QAction* OpenAction = contextMenu->addAction("打开");
    QAction* DeleteAction = contextMenu->addAction("删除");
    // 连接信号槽
    //connect(CopyAction,&QAction::triggered,this,&CustomWindow::CopyActionActionTriggered);
    connect(PasteAction,&QAction::triggered,this,&CustomWindow::PasteActionActionTriggered);
    //connect(ClippingAction,&QAction::triggered,this,&CustomWindow::ClippingActionTriggered);
    //connect(OpenAction,&QAction::triggered,this,&CustomWindow::onOpenActionTriggered);
    connect(DeleteAction,&QAction::triggered,this,&CustomWindow::DeleteActionTriggered);

    //ye
    //显示方式的切换
    QObject::connect(changeway, &QAction::triggered, [=]() {
        // 切换到下一个视图
        int currentIndex = stackedWidget->currentIndex();
        int nextIndex = (currentIndex + 1) % stackedWidget->count();
        stackedWidget->setCurrentIndex(nextIndex);
    });

    //zzh改
    QObject::connect(listView, &QListView::doubleClicked, [&](const QModelIndex &index) {
        // 获取被双击的项的信息
        QFileInfo fileInfo = model->fileInfo(index);
        // 如果是目录，则进入下一层
        if (fileInfo.isDir()) {
            qDebug()<<"zzh="<<fileInfo.filePath();
            selectedIndexes.append(fileInfo.filePath());
            listView->setRootIndex(index);
        } else {
            // 如果是文件，可以执行文件相关的操作
            // 例如打开文件
            //QDesktopServices::openUrl(QUrl::fromLocalFile(fileInfo.absoluteFilePath()));
        }
    });
    QLabel *bottomLabel = new QLabel("   欢迎使用审计移动存储安全平台", this);
    //bottomLabel->setStyleSheet("border: 1px solid black; height: 50px; padding: 5px;");
    layoutMax->addLayout(layout);
    layoutMax->addWidget(bottomLabel);

    resize(800, 470);

}
//ye---//zzh改
void CustomWindow::onButtonClick()
{
    int current = stackedWidget->currentIndex();
    if(current==0){
        qDebug() <<"current==0";
    }
    else if(current==1){
        qDebug() <<"current==1";
        if(selectedIndexes.size()>0){
            QString currentPath = selectedIndexes.at(selectedIndexes.size()-1);
            selectedIndexes.removeLast();
            qDebug() << "Current Path:" << currentPath;
            QString parentPath = QDir(currentPath).absolutePath() + "/..";
            qDebug() << "Current parentPath:" << parentPath;
            listView->setRootIndex(model->index(parentPath));
        }
    }
}

bool CustomWindow::Copyfile(const QString &srcFilePath, const QString &destFilePath)
{
    QProcess* process = new QProcess(this);
    QString program = "xcopy";
    QStringList arguments;
    arguments << srcFilePath << destFilePath << "/I" << "/Y";

    connect(process, QOverload<int, QProcess::ExitStatus>::of(&QProcess::finished), [=](int exitCode, QProcess::ExitStatus exitStatus) {
        process->deleteLater(); // 在处理完成后删除 QProcess 对象
        if (exitStatus == QProcess::NormalExit && exitCode == 0) {
            qDebug() << "File copy completed successfully.";
            // 执行复制完成后的操作
        } else {
            qDebug() << "File copy failed with exit code:" << exitCode;
            // 复制失败的处理
        }
    });

    process->start(program, arguments);

    return true;
}

bool CustomWindow::CopyFolder(const QString &srcFilePath, const QString &destFilePath)
{
    QProcess process;
    QString program = "xcopy";
    QStringList arguments;
    arguments << srcFilePath << destFilePath << "/I" << "/Y" <<"/E";
    process.start(program,arguments);
    process.waitForFinished();
    //QByteArray output = process.readAllStandardOutput();
    QByteArray error = process.readAllStandardError();
    qDebug() << "Standard Error: " << QString::fromUtf8(error);
    if(error==""){
        return true;
    }
    else{
        return false;
    }
}

void CustomWindow::openFile(const QModelIndex &index)
{
    QString filePath = model->fileInfo(index).absoluteFilePath();
    QFileInfo fileInfo(filePath);
    if (fileInfo.isFile()) {
        //QProcess::startDetached(filePath);
        //qDebug() << filePath;
        //QDesktopServices::openUrl(QUrl::fromLocalFile(filePath));
    }
}
//zzh改
void CustomWindow::CopyActionActionTriggered()
{
    int current = stackedWidget->currentIndex();
    QModelIndex currentIndex;
    if(current==0){
        currentIndex = treeView->currentIndex();
    }
    else if(current==1){
        currentIndex = listView->currentIndex();
    }
    QString filePath = model->fileInfo(currentIndex).absoluteFilePath();
    QFileInfo fileInfo(filePath);

    if (fileInfo.isFile()) {
        // 复制文件到剪贴板
        QClipboard* clipboard = QGuiApplication::clipboard();
        QMimeData* mimeData = new QMimeData;
        QList<QUrl> urlList;
        // 将文件路径添加为QUrl对象到列表中
        QString filePath = fileInfo.absoluteFilePath();
        QUrl fileUrl = QUrl::fromLocalFile(filePath);
        qDebug() << "fileUrl is: " << fileUrl;
        urlList.append(fileUrl);

        // 将URL列表设置为剪贴板的MIME数据
        mimeData->setUrls(urlList);
        clipboard->setMimeData(mimeData);
    }
    else if(fileInfo.isDir()){
        // 复制目录内容到剪贴板
        QClipboard* clipboard = QGuiApplication::clipboard();
        QMimeData* mimeData = new QMimeData();
        QList<QUrl> urlList;

        // 将目录本身添加为QUrl对象到列表中
        QUrl dirUrl = QUrl::fromLocalFile(filePath);
        qDebug() << "dirUrl is: " << dirUrl;
        urlList.append(dirUrl);

        // 将URL列表设置为剪贴板的MIME数据
        mimeData->setUrls(urlList);
        clipboard->setMimeData(mimeData);
    }
}

//在线程池中进行复制的回调函数
 void CustomWindow::startCopyProcess(const QString& srcPath, const QString& destPath)
{
    if (Copyfile(srcPath, destPath)) {
        //qDebug() << "Success to copy file: " << destPath;
    } else {
        //qDebug() << "Failed to copy file: " << srcPath;
    }
}


//zzh改
void CustomWindow::PasteActionActionTriggered()
{
    int current = stackedWidget->currentIndex();
    QModelIndex currentIndex;
//    QItemSelectionModel* selectionModel;
//    QModelIndexList selectedIndexes;
    if(current==0){
        currentIndex = treeView->currentIndex();
//         selectionModel =treeView->selectionModel();
//         selectedIndexes =selectionModel->selectedIndexes();
    }
    else if(current==1){
        currentIndex = listView->currentIndex();
    }

    //=====================================================================
    QString destPath = model->fileInfo(currentIndex).absoluteFilePath();
    QFileInfo fileInfo(destPath);
    if (fileInfo.isFile()) {
        destPath = fileInfo.absolutePath();
    }
    qDebug() << "The directory of the current file is: " << destPath;


    //===========================================================================
//    if (!selectedIndexes.isEmpty()) {
//        // 有选中项
//        foreach (QModelIndex index, selectedIndexes) {
//            // 处理选中的索引
//            // 例如，获取选中项的路径：
//            QString filePath = model->fileInfo(index).absoluteFilePath();
//            qDebug() << "选中的项路径：" << filePath;
//        }
//    } else {
//        // 没有选中项
//        qDebug() << "没有选中项";
//    }
//    QString destPath = "D:/usb1/";


    // 获取剪贴板的MIME数据
    const QClipboard* clipboard = QGuiApplication::clipboard();
    const QMimeData* mimeData = clipboard->mimeData();

    if (mimeData->hasUrls()) {
        QList<QUrl> urlList = mimeData->urls();



        //进度条
        int fileNum = urlList.count();
        qDebug() << "fileNum == " << fileNum;
        QProgressDialog progressDialog(this);
        progressDialog.setWindowTitle("复制进度");
        progressDialog.setLabelText("复制文件...");
        progressDialog.setRange(0, fileNum);
        progressDialog.setValue(0);
        progressDialog.setAutoClose(true);
        progressDialog.show();

        // 遍历URL列表，并将每个文件复制到指定目录下
        int i=0;

        foreach (const QUrl& url, urlList) {
            i++;
            QString tmpfilePath = destPath + "/" + url.fileName();
            QFile file(tmpfilePath);
            if (file.exists()) {
                qDebug() << "文件路径存在：" << tmpfilePath;
                QMessageBox msgBox;
                msgBox.setText("文件已存在");
                msgBox.setInformativeText("是否要覆盖该文件？");
                msgBox.setStandardButtons(QMessageBox::Cancel | QMessageBox::Yes);
                msgBox.setDefaultButton(QMessageBox::Cancel);

                int ret = msgBox.exec();
                if (ret == QMessageBox::Yes) {
                    // 用户选择了"覆盖"按钮
                    qDebug() << "用户选择覆盖文件";
                    goto start;
                    // 在这里执行覆盖文件的操作
                } else {
                    // 用户选择了"取消"按钮
                    qDebug() << "用户取消操作";
                    // 在这里执行取消操作的逻辑
                    QCoreApplication::processEvents(); // 处理事件循环，让进度条更新
                    progressDialog.setValue(i); // 更新进度条
                    continue;
                }
            }

            start:
            if (url.isLocalFile()) {
                QString sourcePath = url.toLocalFile();
                QFileInfo fileInfo(sourcePath);
                if (fileInfo.isFile()) {
                    sourcePath.replace("/", "\\");
                    QString destinationPath = destPath.replace("/", "\\");
                    qDebug() << "sourcePath="<<sourcePath;
                    qDebug() << "destinationPath="<<destinationPath;



                    //原来的单线程复制
                    if (Copyfile(sourcePath, destinationPath)) {
                        qDebug() << "Success to copy file: " << destinationPath;
                    } else {
                        qDebug() << "Failed to copy file: " << sourcePath;
                    }
                    //现在线程池进行复制
                    // 在这里执行文件复制的操作
                    // 在这里执行文件复制的操作
//                    QtConcurrent::run([this, sourcePath, destinationPath]() {
//                        startCopyProcess(sourcePath, destinationPath);
//                    });


                    //检查是否是剪切操作，如果是则删除源文件
                    if (mimeData->hasFormat("Preferred DropEffect")) {
                        QByteArray data = mimeData->data("Preferred DropEffect");
                        DWORD dropEffect;
                        memcpy(&dropEffect, data.constData(), sizeof(DWORD));
                        if (dropEffect == DROPEFFECT_MOVE || dropEffect == DROPEFFECT_LINK) {
                            QFile file(sourcePath);
                            if (file.remove()) {
                                qDebug() << "Success to remove file: " << sourcePath;
                            } else {
                                qWarning() << "Failed to remove file: " << sourcePath;
                            }
                        }
                    }
                }
                else if(fileInfo.isDir()){
                    QString folderName = fileInfo.fileName();
                    sourcePath.replace("/", "\\");
                    QString dest = destPath + "/" + folderName;
                    QString destinationPath = dest.replace("/", "\\");
                    qDebug() << "sourcePath="<<sourcePath;
                    qDebug() << "destinationPath="<<destinationPath;
                    if (CopyFolder(sourcePath, destinationPath)) {
                        qDebug() << "Success to copy Folder: " << destinationPath;
                    } else {
                        qDebug() << "Failed to copy Folder: " << sourcePath;
                    }
                    //检查是否是剪切操作，如果是则删除源文件夹
                    if (mimeData->hasFormat("Preferred DropEffect")) {
                        QByteArray data = mimeData->data("Preferred DropEffect");
                        DWORD dropEffect;
                        memcpy(&dropEffect, data.constData(), sizeof(DWORD));
                        if (dropEffect == DROPEFFECT_MOVE || dropEffect == DROPEFFECT_LINK) {
                            QDir dir(sourcePath);
                            if (dir.removeRecursively()) {
                                qDebug() << "Success to remove Directory: " << sourcePath;
                            } else {
                                qWarning() << "Failed to remove Directory: " << sourcePath;
                            }
                        }
                    }
                }

            }
            QCoreApplication::processEvents(); // 处理事件循环，让进度条更新
            progressDialog.setValue(i); // 更新进度条
        }
        progressDialog.close();
    }
}
//zzh改
void CustomWindow::ClippingActionTriggered()
{
    int current = stackedWidget->currentIndex();
    QModelIndex currentIndex;
    if(current==0){
        currentIndex = treeView->currentIndex();
    }
    else if(current==1){
        currentIndex = listView->currentIndex();
    }
    QString filePath = model->fileInfo(currentIndex).absoluteFilePath();
    QFileInfo fileInfo(filePath);
    qDebug() << "fileUrl is: " << fileInfo.filesystemAbsoluteFilePath();
    if (fileInfo.isFile()) {
        // 复制文件到剪贴板
        QClipboard* clipboard = QGuiApplication::clipboard();
        QMimeData* mimeData = new QMimeData;
        // 上传剪切标志到剪贴板
        DWORD dropEffect = DROPEFFECT_MOVE;
        QByteArray dropEffectData(reinterpret_cast<char*>(&dropEffect), sizeof(DWORD));
        mimeData->setData("Preferred DropEffect", dropEffectData);
        clipboard->setMimeData(mimeData);

        QList<QUrl> urlList;
        // 将文件路径添加为QUrl对象到列表中
        QString filePath = fileInfo.absoluteFilePath();
        QUrl fileUrl = QUrl::fromLocalFile(filePath);
        qDebug() << "fileUrl is: " << fileUrl;
        urlList.append(fileUrl);

        // 将URL列表设置为剪贴板的MIME数据
        mimeData->setUrls(urlList);
        clipboard->setMimeData(mimeData);
    }
    else if(fileInfo.isDir()){
        // 复制目录内容到剪贴板
        QClipboard* clipboard = QGuiApplication::clipboard();
        QMimeData* mimeData = new QMimeData();
        // 上传剪切标志到剪贴板
        DWORD dropEffect = DROPEFFECT_MOVE;
        QByteArray dropEffectData(reinterpret_cast<char*>(&dropEffect), sizeof(DWORD));
        mimeData->setData("Preferred DropEffect", dropEffectData);
        clipboard->setMimeData(mimeData);

        QList<QUrl> urlList;
        // 将目录本身添加为QUrl对象到列表中
        QUrl dirUrl = QUrl::fromLocalFile(filePath);
        qDebug() << "dirUrl is: " << dirUrl;
        urlList.append(dirUrl);

        // 将URL列表设置为剪贴板的MIME数据
        mimeData->setUrls(urlList);
        clipboard->setMimeData(mimeData);
    }
}
//zzh改
void CustomWindow::onOpenActionTriggered()
{
    int current = stackedWidget->currentIndex();
    QModelIndex currentIndex;
    if(current==0){
        currentIndex = treeView->currentIndex();
    }
    else if(current==1){
        currentIndex = listView->currentIndex();
    }
    QString filePath = model->fileInfo(currentIndex).absoluteFilePath();
    QFileInfo fileInfo(filePath);
    if (fileInfo.isFile()) {
        QProcess::startDetached(filePath);
        qDebug() << filePath;
        QDesktopServices::openUrl(QUrl::fromLocalFile(filePath));
    }
    else if(fileInfo.isDir()){
        //QProcess::startDetached(filePath);
        treeView->setExpanded(currentIndex, true);
        qDebug() << filePath;
    }
}
//zzh改
void CustomWindow::DeleteActionTriggered()
{
    int current = stackedWidget->currentIndex();
    QModelIndex currentIndex;
    if(current==0){
        currentIndex = treeView->currentIndex();
    }
    else if(current==1){
        currentIndex = listView->currentIndex();
    }
    QString filePath = model->fileInfo(currentIndex).absoluteFilePath();
    QFileInfo fileInfo(filePath);
    if (fileInfo.isFile()) {
        // 删除文件
        QFile file(filePath);
        if (file.remove()) {
            qDebug() << "File removed: " << filePath;
        } else {
            qWarning() << "Failed to remove file: " << filePath;
        }
    }
    else if(fileInfo.isDir()){
        // 删除目录及其所有内容
        QDir dir(filePath);
        if (dir.removeRecursively()) {
            qDebug() << "Directory removed: " << filePath;
        } else {
            qWarning() << "Failed to remove directory: " << filePath;
        }
    }
}

void CustomWindow::uninstallActionTriggered()
{
    QString processName = "app.exe";
    QString command1 = "tasklist";
    QProcess process;
    QStringList arguments1;
    arguments1 << "/FI" << QString("IMAGENAME eq %1").arg(processName);

    process.start(command1, arguments1);
    process.waitForFinished();
    QByteArray output = process.readAllStandardOutput();
    QString outputStr = QString::fromLocal8Bit(output);

    if (outputStr.contains(processName)) {
        qDebug() << processName << "正在运行";
    } else {
        QMessageBox::information(nullptr, "失败", "还没有挂载！");
        return;
    }


    QString program = "taskkill";
    QStringList arguments;
    arguments << "/F" << "/IM" << "app.exe";


    process.start(program, arguments);
    process.waitForFinished();
    // 获取命令执行的输出结果
    output = process.readAllStandardOutput();
    QByteArray error = process.readAllStandardError();

    // 打印输出和错误信息
    qDebug() << "Output:" << output;
    qDebug() << "Error:" << error;
    QMessageBox::information(nullptr, "成功", "操作成功完成！");
    Widget::MountPathList.clear();
    this->close();

}

void CustomWindow::dragEnterEvent(QDragEnterEvent *event)
{
    if (event->mimeData()->hasUrls()) {
        event->acceptProposedAction();
    }
}

//zzh改
void CustomWindow::dropEvent(QDropEvent *event)
{
    const QMimeData *mimeData = event->mimeData();
    if (mimeData->hasUrls()) {
        QList<QUrl> urlList = mimeData->urls();
        //进度条
        int fileNum = urlList.count();
        qDebug() << "fileNum == " << fileNum;
        QProgressDialog progressDialog(this);
        progressDialog.setWindowTitle("复制进度");
        progressDialog.setLabelText("复制文件...");
        progressDialog.setRange(0, fileNum);
        progressDialog.setValue(0);
        progressDialog.setAutoClose(true);
        progressDialog.show();

        // 遍历URL列表，并将每个文件复制到指定目录下
        int i=0;
        foreach (const QUrl &url, urlList) {
            i++;
            QString filePath = url.toLocalFile();
            qDebug() << "Dropped file path: " << filePath;

            //zzh改
            int current = stackedWidget->currentIndex();
            QModelIndex currentIndex;
            QString destPath;

            if(current==0){
                currentIndex = treeView->currentIndex();
                destPath = model->fileInfo(currentIndex).absoluteFilePath();

            }

            else if(current==1){
                if(selectedIndexes.size() == 0){
                    destPath = this->path;
                }
                else{
                    destPath = selectedIndexes.at(selectedIndexes.size()-1);
                }
            }

            qDebug() << "destPath path: " << destPath;
            //验证是否文件是否同名
            //删除路径的System Volume Information字样
            QString target = "System Volume Information";
            destPath.replace(target,"");

            if(destPath == ""){
                destPath = "C:/usb1";
            }

            //会有这样的bug：D:/usb1/test.db/1 - 副本 - 副本 - 副本 - 副本 - 副本 - 副本 - 副本 - 副本 - 副本.txt"
            //解决方法就是先判断是否是文件，如果是文件就获得他的目录路径就可以
            QFileInfo tmpfile(destPath);
            if(tmpfile.isFile()){
                QDir dir = tmpfile.dir();
                QString path = dir.absolutePath();
                destPath = path;
            }





            QString tmpfilePath = destPath + "/" + url.fileName();
            qDebug() << "tmpfilePath: " << tmpfilePath;


            QFile file(tmpfilePath);
            if (file.exists()) {
                qDebug() << "文件路径存在：" << tmpfilePath;
                    QMessageBox msgBox;
                msgBox.setText("文件已存在");
                msgBox.setInformativeText("是否要覆盖该文件？");
                msgBox.setStandardButtons(QMessageBox::Cancel | QMessageBox::Yes);
                msgBox.setDefaultButton(QMessageBox::Cancel);

                int ret = msgBox.exec();
                if (ret == QMessageBox::Yes) {
                    // 用户选择了"覆盖"按钮
                    qDebug() << "用户选择覆盖文件";
                    goto start;
                    // 在这里执行覆盖文件的操作
                } else {
                    // 用户选择了"取消"按钮
                    qDebug() << "用户取消操作";
                    // 在这里执行取消操作的逻辑
                    continue;
                }
            }

        start:

            QFileInfo fileinfo(destPath);
            if (fileinfo.isFile()) {
                destPath = fileinfo.absolutePath();
            }
            QString targetDirectory = destPath;

            qDebug() << "targetDirectory path: " << targetDirectory;

            QFileInfo fileInfo(filePath);
            QString newFilePath = targetDirectory ;
            if(newFilePath == ""){
                newFilePath = "C:/usb1";
            }
            if(QFileInfo(filePath).isDir()){
                QDir dir(filePath);
                newFilePath =newFilePath + "\\" + dir.dirName();
            }

            filePath.replace("/", "\\");
            newFilePath.replace("/", "\\");
            if(QFileInfo(filePath).isFile()){
                Copyfile(filePath, newFilePath);
                qDebug() << "是文件 " << filePath;

            }else{
                CopyFolder(filePath, newFilePath);
                qDebug() << "是文件夹 " << filePath;
            }

            qDebug() << "filePath path: " << filePath;
            qDebug() << "newFilePath path: " << newFilePath;
            QCoreApplication::processEvents(); // 处理事件循环，让进度条更新
            progressDialog.setValue(i);
        }
        progressDialog.close();

        window()->activateWindow();
        window()->raise();
        window()->setFocus(Qt::ActiveWindowFocusReason);
        event->acceptProposedAction();
    }
}

// 重写contextMenuEvent函数
void CustomWindow::contextMenuEvent(QContextMenuEvent* event)
{
    //contextMenu->exec(event->globalPos());
    if (!treeView->rect().contains(treeView->mapFromGlobal(event->globalPos()))) {
        // 鼠标点击位置不在treeView内
        treeView->setCurrentIndex(treeView->rootIndex());
    } else {
        contextMenu->exec(event->globalPos());
    }
}

void CustomWindow::setPath(QString& Path){
    this->path = Path;
}

void CustomWindow::closeEvent(QCloseEvent *event)
{
    //QMessageBox::information(nullptr, "关闭", "关闭软件前请卸载！");
    QString processName = "app.exe";
    QString command1 = "tasklist";
    QProcess process;
    QStringList arguments1;
    arguments1 << "/FI" << QString("IMAGENAME eq %1").arg(processName);

    process.start(command1, arguments1);
    process.waitForFinished();
    QByteArray output = process.readAllStandardOutput();
    QString outputStr = QString::fromLocal8Bit(output);

    if (outputStr.contains(processName)) {
        qDebug() << processName << "正在运行";
    } else {
        //QMessageBox::information(nullptr, "失败", "还没有挂载！");
        return;
    }


    QString program = "taskkill";
    QStringList arguments;
    arguments << "/F" << "/IM" << "app.exe";


    process.start(program, arguments);
    process.waitForFinished();
    // 获取命令执行的输出结果
    output = process.readAllStandardOutput();
    QByteArray error = process.readAllStandardError();

    // 打印输出和错误信息
    qDebug() << "Output:" << output;
    qDebug() << "Error:" << error;
    QMessageBox::information(nullptr, "成功", "U盘卸载成功！");
    Widget::MountPathList.clear();
    event->accept();
}

//zzh改
void MyListView::dragEnterEvent(QDragEnterEvent* event)
{
    // 在这里处理拖拽进入的事件逻辑
    //event->acceptProposedAction();  // 接受拖拽事件
}

void MyListView::dropEvent(QDropEvent* event)
{
    // 在这里处理放下拖拽的事件逻辑
    event->accept();  // 接受放下事件
}

